package com.fjsh.mq.consumer;

import java.io.IOException;

import com.fjsh.consts.QueuesConst;
import com.rabbitmq.client.Channel;
 
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
 
/**
 * RabbitReceiver
 */
@Component
public class MqConsumer {

    /**
     * 扇形队列监听
     * @param message
     * @param channel
     */
    @RabbitHandler
    @RabbitListener(queues = QueuesConst.TEST_FANOUT_QUEUES)
    public void handlerFanout(Message message,Channel channel) throws IOException {
        System.out.println("RabbitReceiver:" + new String(message.getBody()) + "test_fanout_queue");

        // 手动确认ack,因为配置文件设置为手动确认，若此处不手动确认删除队列的话，下次启动还会继续消费
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 直连队列监听
     * @param message
     * @param channel
     */
    @RabbitHandler
    @RabbitListener(queues = QueuesConst.TEST_DIRECT_QUEUE)
    public void handlerDirect(Message message,Channel channel) throws IOException {
        System.out.println("RabbitReceiver:" + new String(message.getBody()) + "test_direct_queue");

        // 手动确认ack,因为配置文件设置为手动确认，若此处不手动确认删除队列的话，下次启动还会继续消费
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 话题队列监听
     * @param message
     * @param channel
     */
    @RabbitHandler
    @RabbitListener(queues = QueuesConst.TEST_TOPIC_QUEUE)
    public void handlerTopic(Message message,Channel channel) throws IOException {
        System.out.println("RabbitReceiver:" + new String(message.getBody()) + "test_topic_queue");

        // 手动确认ack,因为配置文件设置为手动确认，若此处不手动确认删除队列的话，下次启动还会继续消费
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 测试正常队列消费失败
     */
    @RabbitHandler
    @RabbitListener(queues = QueuesConst.TEST_DIRECT_DEAD_QUEUE)
    public void handlerTestQueue(Message message, Channel channel) throws IOException {
        System.out.println("监听到正常队列有消息进来");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 此处为了测试正常队列消费失败了之后，失败的消息会继续路由到死信队列，由死信队列进行消费,所以此处进行拒收消息
        channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);

        // 手动确认ack,因为配置文件设置为手动确认，若此处不手动确认删除队列的话，下次启动还会继续消费
        // channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 若死信队列监听到信息，表示我们的死信队列设置是没有问题的
     */
    @RabbitHandler
    @RabbitListener(queues = QueuesConst.TEST_DEAD_QUEUE)
    public void redirect(Message message, Channel channel) throws IOException {
        System.out.println("监听到死信队列有消息进来");

        // 手动确认ack,因为配置文件设置为手动确认，若此处不手动确认删除队列的话，下次启动还会继续消费
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}